import json
import logging
from datetime import datetime, timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from projects.models import Project, Webhook
from projects.webhook_service import WebhookService

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    help = '每5分钟自动查询项目5分钟内接收到的webhook消息并整理汇总推送'

    def handle(self, *args, **options):
        logger.info('开始执行webhook消息汇总任务')
        
        # 获取当前时间和5分钟前的时间
        now = timezone.now()
        five_minutes_ago = now - timedelta(minutes=5)
        
        # 查询所有项目
        projects = Project.objects.all()
        
        for project in projects:
            # 查找项目中5分钟内接收到的webhook消息
            recent_messages = []
            for message in project.webhook_messages:
                # 解析消息的时间戳
                try:
                    message_time = datetime.fromisoformat(message['timestamp'])
                    # 确保使用相同的时区
                    if message_time.tzinfo is None:
                        message_time = timezone.make_aware(message_time)
                    
                    # 检查消息是否在5分钟内
                    if message_time >= five_minutes_ago and message_time <= now:
                        recent_messages.append(message)
                except Exception as e:
                    logger.error(f'解析消息时间戳失败: {str(e)}')
                    continue
            
            # 如果有5分钟内的消息，进行汇总
            if recent_messages:
                self.summarize_and_push(project, recent_messages)
        
        logger.info('webhook消息汇总任务执行完成')
    
    def summarize_and_push(self, project, messages):
        """整理汇总消息并推送给项目的飞书渠道"""
        try:
            # 整理汇总信息
            summary = {
                'project_id': str(project.id),
                'project_name': project.name,
                'summary_time': timezone.now().isoformat(),
                'message_count': len(messages),
                'messages': messages,
                'summary_note': '请登录平台确认，5分钟内确认的信息，会进行逐级同步'
            }
            
            # 构建汇总文本
            summary_text = f"项目 {project.name} 在过去5分钟内收到了 {len(messages)} 条webhook消息。\n\n"
            summary_text += "消息详情：\n"
            
            for i, msg in enumerate(messages, 1):
                msg_time = datetime.fromisoformat(msg['timestamp'])
                formatted_time = msg_time.strftime('%Y-%m-%d %H:%M:%S')
                
                # 提取消息关键信息
                source = msg.get('source', 'unknown')
                ip = msg.get('ip', 'unknown')
                data_preview = json.dumps(msg.get('data', {}), ensure_ascii=False)[:200] + '...' if len(json.dumps(msg.get('data', {}))) > 200 else json.dumps(msg.get('data', {}), ensure_ascii=False)
                
                summary_text += f"{i}. [{formatted_time}] 来源: {source}, IP: {ip}\n   数据: {data_preview}\n\n"
            
            summary_text += "请登录平台确认，5分钟内确认的信息，会进行逐级同步"
            
            # 获取项目的飞书渠道webhook
            feishu_webhooks = project.webhooks.filter(is_active=True, channel='feishu')
            
            if feishu_webhooks:
                logger.info(f'向项目 {project.name} 的飞书渠道推送消息汇总')
                
                # 触发自定义的'webhook_summary'事件
                for webhook in feishu_webhooks:
                    # 确保webhook配置了'push'事件类型
                    if 'push' in webhook.events:
                        WebhookService.trigger_webhook(
                            'push',
                            {
                                'summary': summary,
                                'summary_text': summary_text
                            },
                            project
                        )
        except Exception as e:
            logger.error(f'汇总和推送消息失败: {str(e)}')